package com.hongyuan.sellfitness.ui.home.view_mode;

import android.app.Application;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;
import com.hongyuan.mvvmhabitx.binding.command.BindingAction;
import com.hongyuan.mvvmhabitx.binding.command.BindingCommand;
import com.hongyuan.mvvmhabitx.bus.RxBus;
import com.hongyuan.mvvmhabitx.bus.RxSubscriptions;
import com.hongyuan.mvvmhabitx.bus.event.SingleLiveEvent;
import com.hongyuan.sellfitness.BR;
import com.hongyuan.sellfitness.R;
import com.hongyuan.sellfitness.base.Constants;
import com.hongyuan.sellfitness.base.CustomViewModel;
import com.hongyuan.sellfitness.data.MyRepository;
import com.hongyuan.sellfitness.data.md5.BaseUtil;
import com.hongyuan.sellfitness.ui.home.activity.UseCouponListActivity;
import com.hongyuan.sellfitness.ui.home.beans.BuyLessonChangeBean;
import com.hongyuan.sellfitness.ui.home.beans.BuyOrderBean;
import com.hongyuan.sellfitness.ui.home.beans.BuyLessonPriceBean;
import com.hongyuan.sellfitness.ui.home.beans.CouponBean;
import com.hongyuan.sellfitness.ui.home.beans.StoreLessonDetailBean;
import com.hongyuan.sellfitness.ui.main.activity.PayActivity;
import com.hongyuan.sellfitness.ui.main.beans.V3SuccessBeans;
import com.hongyuan.sellfitness.utils.BigDecimalUtils;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

public class BuyLessonViewModel extends CustomViewModel<MyRepository> {

    private Disposable mSubscription;

    private  StoreLessonDetailBean bean;

    public ObservableField<StoreLessonDetailBean> entity = new ObservableField<>();
    public ObservableField<CouponBean.ListBean> couponBean = new ObservableField<>();

    public ObservableField<String> cpNum = new ObservableField<>();
    public ObservableField<String> unitPrice = new ObservableField<>();
    public ObservableField<String> allPrice = new ObservableField<>();

    public BuyLessonViewModel(@NonNull Application application, MyRepository model) {
        super(application, model);
    }

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();
    public class UIChangeObservable {
        //改变显示数量
        public SingleLiveEvent<BuyLessonChangeBean> changeShowNum = new SingleLiveEvent<>();
        //通知显示优惠卷信息
        public SingleLiveEvent<String> showCouponName = new SingleLiveEvent<>();
    }

    //给RecyclerView添加ObservableList
    public ObservableList<BuyLessonItmeViewModel> observableList = new ObservableArrayList<>();
    //给RecyclerView添加ItemBinding
    public ItemBinding<BuyLessonItmeViewModel> itemBinding = ItemBinding.of(BR.viewModel, R.layout.item_buy_lesson);


    //减
    public BindingCommand subNum = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            try {
                int classNum;
                try {
                    classNum = Integer.valueOf(cpNum.get());
                }catch (Exception e){
                    e.printStackTrace();
                    classNum = 1;
                }
                classNum--;
                if(classNum < 1){
                    classNum = 1;
                }
                cpNum.set(String.valueOf(classNum));

            }catch (Exception e){
                e.printStackTrace();
            }
        }
    });

    //加
    public BindingCommand addNum = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            int classNum;
            try {
                classNum = Integer.valueOf(cpNum.get());
            }catch (Exception e){
                e.printStackTrace();
                classNum = 0;
            }

            classNum++;
            cpNum.set(String.valueOf(classNum));
        }
    });

    //生成私教课订单
    public BindingCommand goPay = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            clearParams().setParams("jl_mid",String.valueOf(entity.get().getM_id()))
                    .setParams("ocp_num",cpNum.get())
                    .setParams("cp_id",String.valueOf(entity.get().getCp_id()));
            if(BaseUtil.isValue(couponBean.get())){
                setParams("cm_id",String.valueOf(couponBean.get().getCm_id()));
            }
            requestData(Constants.BUY_PRIVITE_COURSE);
        }
    });
    //选取优惠券
    public BindingCommand selectCoupon = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            Bundle bundle = new Bundle();
            bundle.putString("couponFor","3");
            bundle.putString("totalMoney",allPrice.get());
            //bundle.putInt("couponId",couponId);
            bundle.putString("os_id",String.valueOf(entity.get().getOs_id()));
            startActivity(UseCouponListActivity.class,bundle);
        }
    });

    public TextWatcher watcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //只要编辑框内容有变化就会调用该方法，s为编辑框变化后的内容
            if (s.toString().contains(" ")) {
                String[] str = s.toString().split(" ");
                String str1 = "";
                for (int i = 0; i < str.length; i++) {
                    str1 += str[i];
                }

                uc.changeShowNum.setValue(new BuyLessonChangeBean(str1,start));
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            //编辑框内容变化之前会调用该方法，s为编辑框内容变化之前的内容
            Log.i("beforeTextChanged", s.toString());
        }

        @Override
        public void afterTextChanged(Editable s) {
            //编辑框内容变化之后会调用该方法，s为编辑框内容变化后的内容
            if(s.length() > 0){
                try {
                    int snum = Integer.valueOf(s.toString());
                    if(snum > 0){
                        setParams("cp_id",String.valueOf(entity.get().getCp_id()))
                                .setParams("num",s.toString());
                        requestData(Constants.GET_PRICE_BY_NUM);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }

            }

        }
    };

    @Override
    public void onCreate() {
        super.onCreate();

        mSubscription = RxBus.getDefault().toObservable(CouponBean.ListBean.class)
                .observeOn(AndroidSchedulers.mainThread()) //回调到主线程更新UI
                .subscribe(coupon -> {
                    if(coupon != null && BaseUtil.isValue(coupon.getCoupon_money())){
                        uc.showCouponName.setValue(coupon.getCoupon_name());

                        if(couponBean.get() == null || !BaseUtil.isValue(couponBean.get().getCoupon_money())){
                            allPrice.set(BaseUtil.getNoZoon(BigDecimalUtils.sub(allPrice.get(),coupon.getCoupon_money(),2)));
                        }else{
                            allPrice.set(BaseUtil.getNoZoon(BigDecimalUtils.add(allPrice.get(),couponBean.get().getCoupon_money(),2)));
                            allPrice.set(BaseUtil.getNoZoon(BigDecimalUtils.sub(allPrice.get(),coupon.getCoupon_money(),2)));
                        }
                        couponBean.set(coupon);

                    }else{
                        if(couponBean.get() != null && BaseUtil.isValue(couponBean.get().getCoupon_money())){
                            allPrice.set(BaseUtil.getNoZoon(BigDecimalUtils.add(allPrice.get(),couponBean.get().getCoupon_money(),2)));
                        }

                        uc.showCouponName.setValue("");
                        couponBean.set(null);
                    }

                });
        //将订阅者加入管理站
        RxSubscriptions.add(mSubscription);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();

        //取消订阅，防止内存泄漏
        RxSubscriptions.remove(mSubscription);
    }

    @Override
    protected void returnData(int code, Object dataBean) {
        super.returnData(code, dataBean);

        if(code == Constants.GET_COURSE_PRIVITE_INFO){
            bean = (StoreLessonDetailBean)dataBean;
            entity.set(bean);
            cpNum.set(String.valueOf(bean.getCp_num()));
            unitPrice.set(bean.getCp_price());
            allPrice.set(BaseUtil.getNoZoon(BigDecimalUtils.mul(bean.getCp_price(),cpNum.get(),2)));
            for(StoreLessonDetailBean.PriceListBean priceListBean : bean.getPrice_list()){
                BuyLessonItmeViewModel itemViewModel = new BuyLessonItmeViewModel(this,priceListBean);
                observableList.add(itemViewModel);
            }

        }

        if(code == Constants.GET_PRICE_BY_NUM){
            BuyLessonPriceBean priceBean = (BuyLessonPriceBean)dataBean;
            unitPrice.set(BaseUtil.getNoZoon(priceBean.getPrice()));
            allPrice.set(BaseUtil.getNoZoon(BigDecimalUtils.mul(priceBean.getPrice(),cpNum.get(),2)));
        }

        if(code == Constants.BUY_PRIVITE_COURSE){
            BuyOrderBean orderBean = (BuyOrderBean)dataBean;

            V3SuccessBeans beans = new V3SuccessBeans();
            beans.setType(V3SuccessBeans.TYPE.PRIVITECLASS);
            beans.setTitleText("订单");
            beans.setShowText("购买成功");
            beans.setBtn2Text("完成");
            List<V3SuccessBeans.ItemConten> list = new ArrayList<>();

            V3SuccessBeans.ItemConten itemConten = new V3SuccessBeans.ItemConten();
            itemConten.setContent(entity.get().getFt_name()+" / 一对一私教课");
            itemConten.setItemTitle("课程类型:");
            list.add(itemConten);

            itemConten = new V3SuccessBeans.ItemConten();
            itemConten.setContent("¥"+ BaseUtil.getNoZoon(unitPrice.get())+"/节");
            itemConten.setItemTitle("单价:");
            list.add(itemConten);

            itemConten = new V3SuccessBeans.ItemConten();
            itemConten.setContent(cpNum.get()+"节");
            itemConten.setItemTitle("数量:");
            list.add(itemConten);

            itemConten = new V3SuccessBeans.ItemConten();
            itemConten.setContent("¥"+BaseUtil.getNoZoon(allPrice.get()));
            itemConten.setItemTitle("总价:");
            list.add(itemConten);


            if(couponBean.get() != null){
                itemConten = new V3SuccessBeans.ItemConten();
                itemConten.setContent("-¥"+BaseUtil.getNoZoon(couponBean.get().getCoupon_money()));
                itemConten.setItemTitle("优惠:");
                list.add(itemConten);
            }

            beans.setItemContens(list);

            Bundle bundle = new Bundle();
            bundle.putString("payPrice",allPrice.get());
            bundle.putString("payOid",orderBean.getO_id());
            bundle.putSerializable("successBeans",beans);
            startActivity(PayActivity.class,bundle);

            finish();
        }
    }
}
